import { Button } from 'antd'
import { Component } from 'react'

class ErrorBoundary extends Component {
  constructor (props) {
    super(props)
    this.state = {
      hasError: false,
    }
  }

  static getDerivedStateFromError (error) {
    return { hasError: true }
  }

  componentDidCatch (error) {
    // 可以做一些错误的打印
    console.log(error)
  }

  render () {
    const { children } = this.props
    const { hasError } = this.state
    const Ui = (
      <div>
        出错了, 请重试
        <Button type="primary" onClick={() => this.setState({ hasError: false })}>重试</Button>
      </div>
    )
    return hasError ? Ui : children()
  }
}

export default ErrorBoundary
